// pages/qiyezoufangdetail/qiyezoufangdetail.js
const dayjs = require("dayjs");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import gcoord from "../../miniprogram_npm/gcoord/dist/gcoord";
import des from "../../utils/des";
let QR = require("../../utils/createQrCode.js"); // require方式
import config from "../../utils/enum.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    corpCredit: "",
    proInfo: {},
    islodding: false,
    distance: '',
    form: {
      zf_name: "",
      zf_zhiwu: "",
      zf_phone: "",
      zf_date: dayjs(new Date(new Date().getTime())).format("YYYY-MM-DD"),
      zf_date_in: new Date().getTime(),
      zf_case: "",
      zf_state: "",
      zf_img: "",
      addressIsSyn: '是',
      isSynComment: ''
    },
    longitude: '',
    latitude: '',
    zf_date_isshow: false,
    maxDate: new Date().getTime(),
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      console.log(value);
      return value;
    },
    zfdatefilter (type, options) {
      return options.reverse()
    },
    zfstateClickisshow: false,
    statecolumns: ["未走访", "已走访无需求", "已走访有意向", "已走访且授信", "已授信且用信", "有意向未准入"],
    fileList: [
    ],
    agencyName: '',
    onlyView: false,
    userId: '',
    corpType: '',
    contactPhone: '',
    clockList: [] // 打卡记录
  },
  createQrCode: function (content, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    //this.canvasToTempImage 为绘制完成的回调函数，可根据自己的业务添加
    QR.api.draw(content, canvasId, cavW, cavH, this, this.canvasToTempImage);
  },
  getCode () {
    const userInfo = wx.getStorageSync('userInfo')
    if (this.data.proInfo.qrcode == '1') {
     
      // 查看

      // const url = `https://fintech-zscqzy.szjrgzjg.com/#/questionnaire/visit?corpName=${decodeURI(this.data.proInfo.corpName)}&shortName=${decodeURI(this.data.proInfo.shortName)}&corpCredit=${this.data.proInfo.corpCredit}&userId=${userInfo.userId}&type=1`
      // console.log(url, '111')
      // wx.navigateTo({
      //   url: `/sub_webview/visit/visit?url=${url}`,
      // })
      
      wx.navigateTo({
        url: `/sub_webview/visit/visit?corpName=${decodeURI(this.data.proInfo.corpName)}&shortName=${decodeURI(this.data.proInfo.shortName)}&corpCredit=${this.data.proInfo.corpCredit}&userId=${userInfo.userId}&type=1&rootName=interview&myId=${this.data.proInfo.id}`,
      })
    } else {
      console.log(this.data.proInfo,'wode id')
      const qrCodeUrl = `https://fintech-zscqzy.szjrgzjg.com/#/questionnaire/interview?corpName=${decodeURI(this.data.proInfo.corpName)}&shortName=${decodeURI(this.data.proInfo.shortName)}&corpCredit=${this.data.proInfo.corpCredit}&userId=${userInfo.userId}&myId=${this.data.proInfo.id}`
      // const qrCodeUrl = `https://fintech-zscqzy.szjrgzjg.com/#/questionnaire/visit?corpName=${decodeURI(this.data.proInfo.corpName)}&shortName=${decodeURI(this.data.proInfo.shortName)}&corpCredit=${this.data.proInfo.corpCredit}&userId=${userInfo.userId}`
      console.log(qrCodeUrl, 'qrCodeUrlqrCodeUrlqrCodeUrl')
      this.createQrCode(qrCodeUrl, "mycanvas", 270, 270);
    }
  },
  //获取临时缓存图片路径，存入data中
  canvasToTempImage: function (canvasId = "mycanvas") {
    let that = this;
    wx.canvasToTempFilePath({
      canvasId, // 这里canvasId即之前创建的canvas-id
      success: function (res) {
        let tempFilePath = res.tempFilePath;
        // that.setData({
        //   qrcodeUrl: tempFilePath,
        // });
        wx.previewImage({
          current: tempFilePath, // 当前显示图片的http链接
          urls: [tempFilePath] // 需要预览的图片http链接列表
        })
      },
      fail: function (res) { },
    });
  },
  async goQuestion () {
    // 判断是否需要再次定位
    wx.navigateTo({
      url: `/sub_suzhou/question/question?backNum=3&onlyView=''&corpCredit=${this.data.proInfo.corpCredit}&corpName=${this.data.proInfo.corpName}&shortName=${this.data.proInfo.shortName}&questionnaire=${this.data.proInfo.questionnaire ? JSON.stringify(this.data.proInfo.questionnaire) : ''}`,
    });
  },
  // toDetail () {
  //   wx.navigateTo({
  //     url: `/pages/mapDetail/mapDetail?corpKey=${this.data.proInfo.corpCredit}`,
  //   });
  // },
  toDetail (e) {
    if (this.data.onlyView) {
      wx.navigateTo({
        url: `/pages/mapDetail/mapDetail?corpKey=${this.data.proInfo.corpCredit}&latitude=${this.data.latitude}&longitude=${this.data.longitude}`,
      });
    } else {
      wx.navigateTo({
        url: `/pages/mapDetail/mapDetail?corpKey=${this.data.proInfo.corpCredit}&latitude=${this.data.latitude}&longitude=${this.data.longitude}&distance=${this.data.distance}`,
      });
    }
  },
  changeInput(e) {
    this.setData({
      [`form.${e.currentTarget.dataset.id}`]: e.detail.value
    })
  },
  onChangeAdd (e) {
    console.log(e.detail);
    this.setData({
      ['form.addressIsSyn']: e.detail
    })
  },
  editZfCase (e) {
    this.setData({
      ['form.zf_case']: e.detail.value
    })
  },
  zfdateclick () {
    this.setData({
      zf_date_isshow: true
    })
  },
  onInput (e) {
    console.log(e);
  },
  location (e) {
    const longitude = this.transMarker1([
      this.data.proInfo.longitude,
      this.data.proInfo.latitude,
    ])[0];
    const latitude = this.transMarker1([
      this.data.proInfo.longitude,
      this.data.proInfo.latitude,
    ])[1];
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      scale: 18,
    });
  },
  zfdateConfirm (e) {
    console.log(e);
    console.log(dayjs(new Date(e.detail)).format("YYYY-MM-DD"));
    this.setData({
      ['form.zf_date']: dayjs(new Date(e.detail)).format("YYYY-MM-DD"),
      zf_date_isshow: false
    })
  },
  zfdateCancel () {
    this.setData({
      zf_date_isshow: false
    })
  },

  zfstateClick () {
    this.setData({
      zfstateClickisshow: true
    })
  },
  // 中心点坐标转化
  transMarker1 (item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.BD09, // 当前坐标系
      gcoord.GCJ02 // 目标坐标系
    );
    return resae;
  },
  zfstateConfirm (e) {
    console.log(e.detail.value);
    this.setData({
      ['form.zf_state']: e.detail.value,
      zfstateClickisshow: false
    })
  },
  zfstateCancel () {
    this.setData({
      zfstateClickisshow: false
    })
  },
  afterRead (event) {
    console.log(event);
    const {
      file
    } = event.detail;
    console.log(file);
    this.data.fileList.push({
      ...file,
      url: file.url,
      deletable: true,
    })
    this.setData({
      fileList: this.data.fileList
    })

  },
  deleteImg () {
    this.data.fileList.pop()
    this.setData({
      fileList: this.data.fileList,
    })
    getApp().globalData.request("/api/fileApi/cosDelete", {
      url: this.data.form.zf_img
    }, "POST").then(res => {
      console.log(res);
      if (res.code == 200) {
        this.setData({
          ["form.zf_img"]: ""
        })
        wx.showToast({
          title: res.data,
        })
      } else {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  selectImg () {
    var that = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      sizeType: ['original', 'compressed'],
      success (res) {
        console.log(res);
        const tempFilePaths = res.tempFiles
        that.data.fileList.push({
          ...tempFilePaths[0],
          url: tempFilePaths[0].tempFilePath,
          deletable: true,
        })
        that.setData({
          fileList: that.data.fileList,
          islodding: true
        })
        // 上传文件 
        wx.showLoading({
          title: '上传中',
        })
        wx.uploadFile({
          url: 'https://fintech-wx.szjrgzjg.com/api/fileApi/cosUpload',
          filePath: tempFilePaths[0].tempFilePath,
          name: 'file',
          formData: {
            file: tempFilePaths[0],
            folder: "mini_suzhou_visit"
          },
          header: {
            token: wx.getStorageSync("token")
          },
          success (res) {
            var data = des.decrypt(
              JSON.parse(res.data).data,
              "98fbffd1064a4355b8abaacb6fa96f94"
            );
            console.log(JSON.parse(data));
            wx.hideLoading()
            that.setData({
              ["form.zf_img"]: JSON.parse(data).data,
              islodding: false
            })
          },
          fail (err) {
            console.log(err);
          }
        })
      }
    })
  },
  verifyRules () {
    if (!this.data.form.zf_name) {
      wx.showToast({
        title: '请填写联系人姓名',
        icon: 'none'
      })
      return false
    }
    if (!this.data.form.zf_phone) {
      wx.showToast({
        title: '请填写联系方式',
        icon: 'none'
      })
      return false
    }
    if (!this.data.form.zf_case) {
      wx.showToast({
        title: '请填写走访内容',
        icon: 'none'
      })
      return false
    }
    if (this.data.form.addressIsSyn === '否' && !this.data.form.isSynComment) {
      wx.showToast({
        title: '请填写具体说明',
        icon: 'none'
      })
      return false
    }
    return true
  },
  commitBasicInfo () {
    console.log(this.data.form, 'form');
    if (this.verifyRules()) {
      let obj = {
        userId: wx.getStorageSync("userInfo").userId,
        corpCredit: this.data.corpCredit,
        contactPerson: this.data.form.zf_name,
        position: this.data.form.zf_zhiwu,
        contactPhone: this.data.form.zf_phone,
        visitDate: this.data.form.zf_date,
        visitRemark: this.data.form.zf_case,
        visitStatus: this.data.form.zf_state,
        visitPictureUrl: this.data.form.zf_img,
        addressIsSyn: this.data.form.addressIsSyn,
        isSynComment: this.data.form.isSynComment,
      }
      console.log(obj, '提交的参数');
      getApp().globalData.request("/visit/updateVisitCorpBasicInfo", obj, "POST").then(res => {
        console.log(res);
        if (res.code == 200) {
          wx.navigateTo({
            url: `/pages/commitsucceed/commitsucceed?backNum=${2}&text=${"走访情况已提交成功"}`,
          })
        } else {
          wx.showToast({
            title: res.msg,
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    console.log(options, '详情页');
    this.setData({
      corpCredit: options.corpCredit,
      agencyName: options.agencyName,
      longitude: options.longitude,
      latitude: options.latitude,
      distance: options.distance || '',
      onlyView: options.onlyView,
      userId: options.userId,
      corpType: options.corpType,
      contactPhone: options.contactPhone
    })
    let userID = wx.getStorageSync("userInfo").userId
    console.log({
      userId: userID,
      corpCredit: options.corpCredit
    }, 'params')
    getApp().globalData.request("/visit/getVisitCorpInfo", {
      userId: this.data.userId ? this.data.userId : userID,
      corpCredit: options.corpCredit
    }, "POST").then(res => {
      console.log(res, '返回的结果');
      if (res.data.visitPictureUrl) {
        this.data.fileList.push({
          url: res.data.visitPictureUrl,
          deletable: true,
        })
      } else {
        this.data.fileList = []
      }
      // 处理颜色和背景
      let keyList = []
      const keyValues = config.visit_suzhou
      res.data.statusList.forEach(poi => {
        const oneObj = keyValues.find(pr => pr.text === poi)
        keyList.push(oneObj)
        res.data.keyList = keyList
      })
      this.setData({
        proInfo: res.data,
        labelList: res.data.keyList,
        ["form.zf_name"]: res.data.contactPerson,
        ["form.zf_phone"]: res.data.contactPhone,
        ["form.zf_date"]: res.data.visitDate || dayjs(new Date(new Date().getTime())).format("YYYY-MM-DD"),
        ["form.zf_date_in"]: new Date(res.data.visitDate).getTime() || new Date().getTime(),
        ["form.zf_case"]: res.data.visitRemark,
        ["form.zf_state"]: res.data.visitStatus,
        ["form.zf_img"]: res.data.visitPictureUrl,
        ["form.addressIsSyn"]: res.data.addressIsSyn || '是',
        ["form.isSynComment"]: res.data.isSynComment,
        ["form.zf_zhiwu"]: res.data.position,
        fileList: this.data.fileList,
        clockList: res.data.clockList
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {

  }
})